<?php

/*
* Plugin Name: Gforms No Duplication on multipart fields
* Plugin URI: https://notabug.org/wp/gform-multiple-field-no-duplicate
* Description: Gforms No Duplication on multipart fields
* Author: Saeb Molaee
* Version: 1.2
* Author URI: https://saeb.id.ir/
* Text Domain: gform-multiple-field-no-duplicate
* Domain Path: /languages
*/

if (!class_exists('GFAPI')) {
	die();
}
class GFormsNoDuplicationOnMultipartField
{
	private static $instance;
	const domain  = 'gform-multiple-field-no-duplicate';
	public static function get_instance()
	{
		if (self::$instance == null) {
			self::$instance = new GFormsNoDuplicationOnMultipartField();
		}
		return self::$instance;
	}
	public static function __($text, $domain = self::domain)
	{
		return __($text, $domain);
	}
	static function _load_plugin_textdomain()
	{
		load_plugin_textdomain(self::domain, false, dirname(plugin_basename(__FILE__)) . '/languages');
	}
	function validate_($result, $value, $form, $field)
	{
		$f = array_values(array_filter($form['fields'], function ($field_) {
			return $field_['id'] == 23;
		}))[0]['defaultValue'];
		$criteria = array();
		$criteria['status'] = 'active';
		$criteria['field_filters'] = array();
		$criteria['field_filters']['mode'] = 'all';
		$criteria['field_filters'][] = array(array("key" => "23", "value" => $f), array("key" => "1", "value" => $value));
		$criteria = array(
			'status'        => 'active',
			'field_filters' => array(
				'mode' => 'all',
				array(
					'key'   => '1',
					'value' => $value
				),
				array(
					'key'   => '23',
					'value' => $f
				)
			)
		);
		// 	var_dump($criteria);
		$e = GFAPI::count_entries($form['id'], $criteria);
		// 	    var_dump($e);
		if ($e > 0) {
			$result['is_valid'] = false;
			$result['message'] = "{$result['message']} شما قبلا به $f ثبت کردید";
		}
		return $result;
	}
	private function __construct()
	{
		add_action('init', array($this, '_load_plugin_textdomain'));
		add_filter('gform_field_validation_32_1', array($this, 'validate_'), 10, 4);
	}
}
GFormsNoDuplicationOnMultipartField::get_instance();
